<?
	class c_default_controller extends c_base_controller
	{
		function __construct()
		{
			parent::__construct();
			
			global $mvc;
			$mvc->theme->name = 'extended'; // TODO: Подумать над темизацией
		}
	
	
		function page($args)
		{
			global $mvc;
			
			$page = new c_page_model($args[2]);
			
			if ($page->exists)
			{
				$mvc->data['page'] = $page->data;
				$ins = new c_insertion_controller();
				$ins->_call($page->data['template']);
			}
			else
			{
				return 'There is no page '.$args[2].'.';
			}
		}
	
		public function go($item, $mode, $addon)
		{
			if ( ($item['_level'] > 0) && ($mode == 0) )
				return '<div style="padding-left:'.(($item['_level'] - 1)*10).'">'.$item['pagetitle'].'</div>'."\n";
		}
		
		function poitree($args)
		{
			global $mvc;
			$tb = new c_tree_util();// $mvc->load_module('tree');
			
			$mvc->bm->add('bef get data');

			$data = $mvc->db->get_data($mvc->parse('SELECT id, parent, pagetitle as name FROM {dbpref}site_content'));
			$mvc->bm->add('beg get data');
		
			$tb->config['fpid'] = 'parent';
			$tree = $tb->build($data);	
			$mvc->bm->add('aft build');

			echo $tb->render($tree, '<ul>|</ul>', '<li>{name}|</li>');
			//print_r($tree);
			
			$mvc->bm->add('finish');
			echo $mvc->view->render('system/bm_default', $mvc->bm->points);
			echo $mvc->view->render('system/mody_messages', $mvc->messages);
		}
		
		function view($args)
		{
			//$ins = new c_insertion_util();
			//$ins->vars = array('a' => 1, 'b' => 2, 'a1' => 222);
			//global $mvc;
			//$ins->vars['mvc'] = $mvc;
			
			/* $ins->insertions['notempty'] = '<? echo ($this->v("v1")) ? $this->v("v1") : $this->v("v2"); ?>'; */
		
			global $mvc;
					
			$view = new c_storage_controller();
			$view->create('menu_views');
			echo $view->render();
			
			/*
			$data = $mvc->db->get_data('SELECT * FROM views');
			foreach($data as $k => $v)
			{
				print_r($v['view_name']. ' ' .$v['view_title'].'<br>');
			}
			*/
			
			$name = mysql_escape_string($_REQUEST['view']);
			
			$this->view = new c_storage_controller();
			$this->view->create($name);
			$view_id = (int)$this->view->params['id'];
			if (($view_id  == 1) || ($view_id  == 2) || ($view_id  == 4))
				$mvc->redirect($this->base_url);
			
			$this->view->base_url = $this->base_url.'view/';
			$html = $this->view->_index($args);
			
			$view_id = (int)$this->view->params['id'];
			if (($view_id  == 1) || ($view_id  == 2) || ($view_id  == 4))
				$mvc->redirect($this->base_url);

			return $html;
			
			//return $this->view->render();
			return;
			//$this->view->name = $name;	
			
			//$this->table = new c_table_model($name);
			//$this->data = $mvc->db->get_data('SELECT * FROM '.$name);			
						
			return $this->show('view');
			//print_r($this->table);			
		}
		
		function edit($args)
		{
			global $mvc;
			$name = mysql_escape_string($_REQUEST['name']);
			$this->table = new c_table_model($name);
			$id = (int)$args['f_id'];
			if ($id)
				$this->data = $mvc->db->get_row($name, $id);
				
			return $this->show('edit');
		}
		
		function save($args)
		{
			global $mvc;
			$name = mysql_escape_string($_REQUEST['name']);
			$mvc->db->set_row($name, $mvc->extract_data($_REQUEST, '/^f_(\\w+)$/'));
			
			//$mvc->db->set_row($name, );
			//$name = mysql_escape_string($_REQUEST['name']);
			//$this->table = new c_table_model($name);
			return $this->view($args);
		}
		
		function delete($args)
		{
			global $mvc;
			$name = mysql_escape_string($_REQUEST['name']);
			$id = (int)$args['f_id'];
			$mvc->db->del_row($name, $id);
			
			return $this->view($args);
		}
		
		function users($args)
		{
			global $mvc;
			
			// Защита от попытки редактировать роль. Перекинем на список.
			if (substr($args['name'], 0, 1) == '_') $args[2] = '';
			
			// Список ролей для шаблона.
			$users = new c_mvc_user_model();
			$this->user_roles = array('_admin' => 'Администратор', '_editor' => 'Редактор', '_manager' => 'Менеджер', '_all' => 'Пользователь');
			
			if ($args['name'])
				$user = new c_mvc_user_model($args['name']);
			else
				$user = new c_mvc_user_model();
				
			$this->user_name = $user->name;
			$this->user_role = $user->config['inherits'][0];
			
			if ($args[2] == 'edit')
			{				
				$this->show('users_edit');
				return;
			}
			
			elseif ($args[2] == 'save')
			{
				$user->config['inherits'] = array($args['role']);
				$user->password = md5($args['password']);
				$user->save();
			}
			
			elseif ($args[2] == 'del')
			{
				$user->kill();				
			}

			{				
				$this->users = $users->get_list('user');
				$this->show('users');
			}
		}
		
		function report($args)
		{
			/*
			$linkage = new c_linkage_model();
			global $mvc;
			
			$linkage->attach('spents', 1, 'workers', 3);
			$linkage->attach('spents', 2, 'workers', 3);
			$linkage->attach('spents', 2, 'workers', 4);
			
			$sql = $linkage->makeSql('SELECT workers.*, spents.sum_ FROM workers, (linked:spents,workers,workers.id) AND spents.sum_ > 100');
			print_r($mvc->db->get_data($sql));
			*/

			
			
		
			if (!isset($args['name'])) return $this->index($args);
			
			$args[1] = mysql_escape_string($args[1]);
			$args[2] = mysql_escape_string($args[2]);
			$workers_id = (int)$args['worker'];
			$car_id = (int)$args['car'];
			
			
			global $mvc;
			
			$this->args = $args;
			
			if ($args['name'] == 'payments')
			{
				$where = '';
				if ($args['date1']) $where .= ' AND date_ >= "'.$args['date1'].'"';
				if ($args['date2']) $where .= ' AND date_ <= "'.$args['date2'].'"';
				if ($where) $where = ' WHERE 1 '.$where;
				
				$this->report = array();
				$this->report['title'] = 'Отчет 1. Заказы по датам';
				$this->report['titles'] = array('Дата', 'Оплаченных', 'Сумма', 'Не оплаченных', 'Сумма', 'Всего', 'Сумма');
				unset($this->report['fields']);
				$this->report['data'] = array();

				$sql = 'SELECT date_, 
					(SELECT COUNT(id) FROM orders o WHERE o.date_=orders.date_ AND payed=1),
					(SELECT SUM(money) FROM orders o WHERE o.date_=orders.date_ AND payed=1),
					(SELECT COUNT(id) FROM orders o WHERE o.date_=orders.date_ AND payed=0),
					(SELECT SUM(money) FROM orders o WHERE o.date_=orders.date_ AND payed=0),
					count(id), sum(money) FROM orders '.$where.' GROUP BY date_ ORDER BY date_';
				$this->report['data'] = $mvc->db->get_data($sql);
				
				
				if (!$where) $where = 'WHERE 1 ';
				$sql = 'SELECT "Итого", 
					(SELECT COUNT(id) FROM orders o '.$where.' AND payed=1),
					(SELECT SUM(money) FROM orders o '.$where.' AND payed=1),
					(SELECT COUNT(id) FROM orders o '.$where.' AND payed=0),
					(SELECT SUM(money) FROM orders o '.$where.' AND payed=0),
					count(id), sum(money) FROM orders '.$where;
				$this->report['data'][] = $mvc->db->get_data($sql, true);
				

				return $this->show('report');
			}
			
			// Отчет по грузчикам, во скольких заказах учавтсвовал и сколько денего получит.
			elseif ($args['name'] == 'lifters')
			{
				$where = '';
				if ($args['date1']) $where .= ' AND date_ >= "'.$args['date1'].'"';
				if ($args['date2']) $where .= ' AND date_ <= "'.$args['date2'].'"';
				if ($where) $where = ' WHERE 1 '.$where;
				
				$this->report = array();
				$this->report['title'] = 'Отчет 2. Зарплата грузчиков';
				$this->report['titles'] = array('ФИО', 'Участие в заказах', 'Сумма на руки');
				$this->report['fields'] = array('fio', 'zakazov', 'gets');
				$this->report['data'] = array();
			
				$sql = 'SELECT 
						o.lifter, o.money, 
						o.money / ( CHAR_LENGTH(o.lifter)-CHAR_LENGTH(REPLACE(o.lifter, ",", ""))+1 ) * 0.3 as get
					FROM orders o '.$where;

				$data = $mvc->db->get_data($sql);

				$workers_data = $mvc->db->get_data('SELECT id, fio, 0 as zakazov, 0 as gets FROM workers ORDER BY fio');
				$workers = array();
				foreach($workers_data as $k => $row)
						$workers[$row['id']] = $row;

				foreach($data as $k => $row)
				{
						$lifters = explode(',', $row['lifter']);
						foreach($lifters as $lifter_id)
						{
								if ((int)$lifter_id != 0)
								{
										$workers[$lifter_id]['zakazov']++;
										$workers[$lifter_id]['gets'] += $row['get'];
								}
						}
				}			

				$this->report['data'] = $workers;
				return $this->show('report');
			}
			
			// Отчет по грузчикам, кто когда в каких заказах учавствовал.
			elseif ($args['name'] == 'lifters2')
			{
				$where = '';
				if ($args['date1']) $where .= ' AND date_ >= "'.$args['date1'].'"';
				if ($args['date2']) $where .= ' AND date_ <= "'.$args['date2'].'"';
				if ($where) $where = ' WHERE 1 '.$where;
				
				$this->report = array();
				$this->report['title'] = 'Отчет 3. Активность грузчиков';
				$this->report['titles'] = array('Дата', 'ФИО', 'Откуда', 'Куда');
				$this->report['fields'] = array('date_', 'lifter', 'addr_start', 'addr_finish');
				$this->report['data'] = array();
			
				$sql = 'SELECT * FROM orders o '.$where;
				$data = $mvc->db->get_data($sql);
				
				foreach($data as $k => $row)
				{
					$sql = 'SELECT * FROM workers WHERE id IN ('.$row['lifter'].')';
					$lifters_data = $mvc->db->get_data($sql);					
					$lifters = array();
					foreach($lifters_data as $row)
					{
						$lifters[] = $row['fio'];
					}
					
					$lifters = implode(', ', $lifters);
					$data[$k]['lifter'] = $lifters;
				}			
				
				//echo '<pre>';
				//print_r($data);
				
				$this->report['data'] = $data;
				return $this->show('report');
			}
			
			// Отчет по 1 грузчику, когда в каких заказах учавствовал сколько заработал.
			elseif ($args['name'] == 'lifters3')
			{
				$where = '';
				if ($args['date1']) $where .= ' AND date_ >= "'.$args['date1'].'"';
				if ($args['date2']) $where .= ' AND date_ <= "'.$args['date2'].'"';
				if ($where) $where = ' WHERE 1 '.$where;
				
				$this->report = array();
				$this->report['title'] = 'Отчет 4. История грузчика';
				$this->report['titles'] = array('Дата', 'Откуда', 'Куда', 'Сумма на руки');
				$this->report['fields'] = array('date_', 'addr_start', 'addr_finish', 'get');
				$this->report['data'] = array();
				// Работники для выбора.
				$this->report['workers'] = $mvc->db->get_data('SELECT * FROM workers');				
			
				$sql = 'SELECT o.*,
						o.leader, o.money, 
						ROUND(o.money * 0.3 / ( CHAR_LENGTH(o.leader)-CHAR_LENGTH(REPLACE(o.leader, ",", ""))+1 )) as get
					FROM orders o '.$where;

				$data = $mvc->db->get_data($sql);

				$workers_data = $mvc->db->get_data('SELECT id, fio, 0 as zakazov, 0 as gets FROM workers ORDER BY fio');
				$workers = array();
				foreach($workers_data as $k => $row)
						$workers[$row['id']] = $row;

				$orders = array();
				$sum = 0;
				foreach($data as $k => $row)
				{
					$lifters = explode(',', $row['lifter']);
					
					if (array_search($args['worker'], $lifters) !== false)
					{
						$orders[] = $row;
						$sum += $row['get'];
					}
				}
				$orders[] = array('date_' => 'Итого', '', '', 'get' => $sum);
				
				$this->report['data'] = $orders;
				return $this->show('report');
			}
			
			
			elseif ($args['name'] == 'zatrati_po_statyam')
			{
				$where = '';
				if ($args['date1']) $where .= ' AND date_ >= "'.$args['date1'].'"';
				if ($args['date2']) $where .= ' AND date_ <= "'.$args['date2'].'"';
				if ($where) $where = ' WHERE 1 '.$where;
				
				$this->report = array();
				$this->report['title'] = 'Отчет 5. Затраты по статьям';
				$this->report['titles'] = array('Статья', 'Сотрудник', 'Машина', 'Сумма');
				$this->report['fields'] = array('spentname', 'worker', 'car', 'summa');
				$this->report['data'] = array();
				// Работники для выбора.
				$this->report['workers'] = $mvc->db->get_data('SELECT * FROM workers');				
				// Машина для выбора.
				$this->report['cars'] = $mvc->db->get_data('SELECT * FROM cars');				
			
				$where2 = $where ? $where : 'WHERE 1 ';
				if ($args['worker']) $where2 .= ' AND workers.id='.(int)$args['worker'];
				if ($args['car']) $where2 .= ' AND cars.id='.(int)$args['car'];				
				
				$sql = 'SELECT sum(spents.sum_) as summa, workers.fio as worker, spentnames.name as spentname, cars.name as car'.
					' FROM spents, spentnames, cars, workers '.
					$where2.' AND spents.spentnames_id=spentnames.id AND spents.workers_id=workers.id AND spents.cars_id=cars.id'.
					' GROUP BY spentname, worker, car';
					
				$data = $mvc->db->get_data($sql);

				// Итог.
				$sql = 'SELECT sum(spents.sum_) as summa, "", "Итого" as spentname, "" as car'.
					' FROM spents, spentnames, cars, workers '.
					$where2.' AND spents.spentnames_id=spentnames.id AND spents.workers_id=workers.id AND spents.cars_id=cars.id';

				$data[] = $mvc->db->get_data($sql, true);

			
				$this->report['data'] = $data;
				return $this->show('report');
			}
			
			elseif ($args['name'] == 'rentabelnost_reklami')
			{
				$where = '';
				if ($args['date1']) $where .= ' AND date_ >= "'.$args['date1'].'"';
				if ($args['date2']) $where .= ' AND date_ <= "'.$args['date2'].'"';
				if ($where) $where = ' WHERE 1 '.$where;
				
				$this->report = array();
				$this->report['title'] = 'Отчет "Рентабельность рекламы"';
				$this->report['titles'] = array('Источник рекламы', 'Сумма затрат', 'Количество заказов', 'Доход от заказов', 'Коэффициент рентабельности');
				$this->report['fields'] = array('name', 'spent', 'orders_count', 'earned', 'coef');
				$this->report['data'] = array();
			
				$sql = '
					SELECT adverts.name as name, 
						(SELECT sum(spents.sum_) FROM spents, spentnames WHERE spents.spentnames_id=spentnames_id AND spentnames.name=adverts.name) as spent,
						count(orders.money) as orders_count,
						sum(orders.money) as earned,
						sum(orders.money) / (SELECT sum(spents.sum_) FROM spents, spentnames WHERE spents.spentnames_id=spentnames_id AND spentnames.name=adverts.name) *0.1 as coef
					FROM adverts
					LEFT JOIN orders ON orders.adverts_id=adverts.id
					'.$where.'
					GROUP BY adverts.name';			
			
				$data = $mvc->db->get_data($sql);
				
				$this->report['data'] = $data;
				return $this->show('report');
			}									
		}
		
		function print_order($args)
		{
			global $mvc;
			$rowid = (int)$args[2];
			
			$mvc->theme->name = 'default';
			
			$sql = 'SELECT * FROM orders WHERE id='.$rowid;
			$this->order['data'] = $mvc->db->get_data($sql, true);
			$this->order['data']['leader'] = $mvc->db->get_data('SELECT fio FROM workers WHERE id = '.$this->order['data']['leader'], true);
			$this->order['data']['leader'] = $this->order['data']['leader']['fio'];
			$this->order['data']['lifter'] = $mvc->db->get_data('SELECT * FROM workers WHERE id IN ('.$this->order['data']['lifter'].')');
			//print_r($this->order['data']['lifter']);
			//$this->order['data'] = $this->order['data'][0];
			
			$this->order['adverts'] = $mvc->db->get_data('SELECT * FROM adverts');
			
			return $this->show('print_order');
			//echo '<pre>';
			//print_r($data);
		}
		
		function login($args)
		{
			$username = isset($_REQUEST['username']) ? $_REQUEST['username'] : '';
			$password = isset($_REQUEST['password']) ? $_REQUEST['password'] : '';
			
			$user = new c_mvc_user_model($username);
			
			if ($user->login($password))
			{
				global $mvc;
				$mvc->redirect($this->base_url);
			}
			else
				return 'Login error';
		}
		
		function logout($args)
		{
			global $mvc;
			$mvc->user->logout();
			$mvc->redirect($this->base_url);
			return '';
		}
		
		function index($args)
		{
			global $mvc;			
			//echo $this->show('index');
			//$storage = new c_storage_controller();
			//$storage->base_url = $this->base_url.'view';
			//echo $storage->_index(array('view' => 'orders_list'));
			//$args['view'] = 'orders_list';
			//return $this->view($args);
			$mvc->redirect('default/view?view=orders_list');
			return '';
			
			//$mvc->parse('<a href="{base_url}poitree">poitree</a>')
			//echo $mvc->parse('<a href="{base_url}manager">manager</a>');
			//$parser = $mvc->load_module('insertion');
			
			$mvc->bm->add('finish');
			//echo $mvc->view->render('system/bm_default', $mvc->bm->points);
			//echo $mvc->view->render('system/mody_messages', $mvc->messages);
			return;
			
			//$this->test_tree();
			
			/*
			$parser = new CInsertion_util();
			
			
			$parser = $mvc->load_module('insertion');
			
			$parser->setVar('x', array('a' => 1, 's' => 2));
			$parser->setIns('valentin', '<? echo "bormintal ".$this->parse($this->getVar("x")); ?>');
			$parser->setIns('test', 'test');
			$parser->debug = true;
			
			$mvc->bm->add('bef parse');
			//echo $parser->parse('hallo world {{x.a}} {{x.d}} [[valentin: x=`[[page: id=`10`]]`]] [[page.func: 0=`150`]] ');
			echo $parser->parse('[[page.func: id=``]]');
			$mvc->bm->add('aft parse');
			
			echo '<pre>';
			print_r($parser->report);
			echo '</pre>';
			

			
			echo $mvc->parse('{base_url}');


			// Список таблиц.
			//$tables = $mvc->db->list_tables('stor', 'name');
			//echo $view->render('table', $tables);
			
			$table = 'stor_aaa';
			
			// Структура таблицы.
			//$fields = $mvc->db->get_fields($table);
			//echo $view->render('fields', $fields);
			

			//$fields['f2']['comment'] = 'Comment of f2 :)';
			//$mvc->db->set_fields($table, $fields);
			
			//$mvc->db->query('ALTER TABLE stor_aaa COMMENT="Барабашка"'  ,false);
			
			
			
			//$taxonomy = $mvc->load_module('taxonomy');
			
			/*
			
			// 1. Получить tv-параметры документа 23.
			$taxonomy->config['table'] = $mvc->parse('{dbpref}site_tmplvar_contentvalues');
			$taxonomy->config['ptable'] = '{dbpref}site_content';
			$taxonomy->config['ctable'] = '{dbpref}site_tmplvars';
			$taxonomy->config['pname'] = '';
			$taxonomy->config['cname'] = '';
			$taxonomy->config['pid'] = 'contentid';
			$taxonomy->config['cid'] = 'tmplvarid';
			
			$data = $taxonomy->get_data('SELECT {links}.value, {ptable}.id FROM {from} WHERE {linkage} AND {ptable}.id=23');
			echo '<pre>';
			print_r($data);
			echo '</pre>';
			
			// 2. Получить tv параметры документов с шаблоном 4.
			$taxonomy->config['table'] = $mvc->parse('{dbpref}site_tmplvar_contentvalues');
			$taxonomy->config['ptable'] = '{dbpref}site_content';
			$taxonomy->config['ctable'] = '{dbpref}site_tmplvars';
			$taxonomy->config['pname'] = '';
			$taxonomy->config['cname'] = '';
			$taxonomy->config['pid'] = 'contentid';
			$taxonomy->config['cid'] = 'tmplvarid';
			
			$data = $taxonomy->get_data('SELECT {links}.* FROM {from} WHERE {linkage} AND {ptable}.template=5');
			echo '<pre>';
			print_r($data);
			echo '</pre>';
			
			// 3. Получить документы у которых есть tv 3.
			$taxonomy->config['table'] = $mvc->parse('{dbpref}site_tmplvar_contentvalues');
			$taxonomy->config['ptable'] = '{dbpref}site_content';
			$taxonomy->config['ctable'] = '{dbpref}site_tmplvars';
			$taxonomy->config['pname'] = '';
			$taxonomy->config['cname'] = '';
			$taxonomy->config['pid'] = 'contentid';
			$taxonomy->config['cid'] = 'tmplvarid';
			
			$data = $taxonomy->get_data('SELECT {ptable}.pagetitle, {links}.value FROM {from} WHERE {linkage} AND {ctable}.name="tv3"');
			echo '<pre>';
			print_r($data);
			echo '</pre>';
			*/
			
			/*
			// 4. Привязать документ 215 к документу 23.
			$taxonomy->config['table'] = $mvc->parse('{dbpref}owners');
			$taxonomy->config['ptable'] = '{dbpref}site_content';
			$taxonomy->config['ctable'] = '{dbpref}site_content';
			$taxonomy->config['pname'] = 'pname';
			$taxonomy->config['cname'] = 'cname';
			$taxonomy->config['pid'] = 'pid';
			$taxonomy->config['cid'] = 'cid';
			
			if (!$taxonomy->attached('215', '23'))
				$taxonomy->attach('215', '23');
			echo '<pre>';
			//print_r($data);
			echo '</pre>';
			*/
			
			
			/*
			// 5. Получить документы привязанные к 23.
			$taxonomy->config['table'] = $mvc->parse('{dbpref}owners');
			$taxonomy->config['ptable'] = '{dbpref}site_content';
			$taxonomy->config['ctable'] = '{dbpref}site_content';
			$taxonomy->config['pname'] = 'pname';
			$taxonomy->config['cname'] = 'cname';
			$taxonomy->config['pid'] = 'pid';
			$taxonomy->config['cid'] = 'cid';
			
			$data = $taxonomy->get_data('SELECT _ctable.id, _ctable.pagetitle FROM {from} WHERE {linkage}');
			echo '<pre>';
			print_r($data);
			echo '</pre>';
			*/
			
			// Надо сформировать переменные {from} и {where} так

			// Общие
			// {pid} => {links}.{fpid}
			// {cid} => {links}.{fcid}
			// {pname} => {links}.{fpname}
			// {cname} => {links}.{fcname}

			// {from} => {ptable}, {ctable}, {links}
			// {linkid} => {pid}={ptable}.id AND {cid}={ctable}.id
			// {linkname} => {pname}='{ptable}' AND {cname}='{ctable}'
			// {where} => {linkid} [ AND {linkname} ]
			
			// 1. Выборка детей.
			// 1.1. Без родительской таблицы (есть id родителя).
			// SELECT {ctable}.* FROM {ctable}, {links} WHERE {linkid} AND {pid}=23
			// DELETE FROM {links} WHERE {pid}=23 AND {pname}='{ptable}'
			
			/*
			// 6. Отвязать все от документа 23.
			$taxonomy->config['links'] = $mvc->parse('{dbpref}owners');
			$taxonomy->config['ptable'] = '{dbpref}site_content';
			$taxonomy->config['ctable'] = '{dbpref}site_content';
			$taxonomy->config['fpname'] = 'pname';
			$taxonomy->config['fcname'] = 'cname';
			$taxonomy->config['fpid'] = 'pid';
			$taxonomy->config['fcid'] = 'cid';
			
			$mvc->bm->add('prepare');
			
			//$data = $taxonomy->get_data('DELETE FROM {links} WHERE {pid}=23');
			$query = $taxonomy->make_sql('SELECT {ctable}.pagetitle FROM {from} WHERE {where}');
			$mvc->bm->add('prepared');

			$data = $mvc->db->get_data($query);
			echo $sql;
			echo '<pre>';
			print_r($data);
			echo '</pre>';
			*/


			/*
			// 1. Получить tv-параметры документа 23.
			$taxonomy->config['links'] = $mvc->parse('{dbpref}site_tmplvar_contentvalues');
			$taxonomy->config['ptable'] = '{dbpref}site_content';
			$taxonomy->config['ctable'] = '{dbpref}site_tmplvars';
			$taxonomy->config['fpname'] = '';
			$taxonomy->config['fcname'] = '';
			$taxonomy->config['fpid'] = 'contentid';
			$taxonomy->config['fcid'] = 'tmplvarid';
			
			//$data = $taxonomy->get_data('SELECT {links}.value, {ptable}.id FROM {from} WHERE {linkage} AND {ptable}.id=23');
			$query = $taxonomy->make_sql('SELECT {links}.value, {ptable}.id FROM {from} WHERE {where} AND {pid}=23 ORDER BY {links}.value');
			echo $query;
			$data = $mvc->db->get_data($query);
			echo '<pre>';
			print_r($data);
			echo '</pre>';
			*/
			
			/*
			// 2. Получить tv параметры документов с шаблоном 5.
			$taxonomy->config['links'] = $mvc->parse('{dbpref}site_tmplvar_contentvalues');
			$taxonomy->config['ptable'] = '{dbpref}site_content';
			$taxonomy->config['ctable'] = '{dbpref}site_tmplvars';
			$taxonomy->config['fpname'] = '';
			$taxonomy->config['fcname'] = '';
			$taxonomy->config['fpid'] = 'contentid';
			$taxonomy->config['fcid'] = 'tmplvarid';
			
			$data = $taxonomy->get_data('SELECT {ctable}.*, {links}.value FROM {from} WHERE {where} AND {ptable}.template=5');
			echo '<pre>';
			print_r($data);
			echo '</pre>';
			*/
			
			/*
			// 3. Получить документы у которых есть tv 3.
			$taxonomy->config['table'] = $mvc->parse('{dbpref}site_tmplvar_contentvalues');
			$taxonomy->config['ptable'] = '{dbpref}site_content';
			$taxonomy->config['ctable'] = '{dbpref}site_tmplvars';
			$taxonomy->config['pname'] = '';
			$taxonomy->config['cname'] = '';
			$taxonomy->config['pid'] = 'contentid';
			$taxonomy->config['cid'] = 'tmplvarid';
			
			$data = $taxonomy->get_data('SELECT {ptable}.pagetitle, {links}.value FROM {from} WHERE {linkage} AND {ctable}.name="tv3"');
			echo '<pre>';
			print_r($data);
			echo '</pre>';
			*/
			
			/*
			// 4. Привязать документ 215 к документу 23.
			$taxonomy->config['links'] = $mvc->parse('{dbpref}owners');
			$taxonomy->config['ptable'] = '{dbpref}site_content';
			$taxonomy->config['ctable'] = '{dbpref}site_content';
			$taxonomy->config['fpname'] = 'pname';
			$taxonomy->config['fcname'] = 'cname';
			$taxonomy->config['fpid'] = 'pid';
			$taxonomy->config['fcid'] = 'cid';
			
			echo $taxonomy->attach(215, '23');
			echo $taxonomy->attach(216, '23');
			echo $taxonomy->attach(217, '23');
			echo $taxonomy->attach(218, '23');
			*/
			
			/*
			// 4. Привязать poi 35 к новостям 49,50,51.
			$taxonomy->config['links'] = $mvc->parse('{dbpref}owners');
			$taxonomy->config['ptable'] = 'stor_news';
			$taxonomy->config['ctable'] = 'stor_poi';
			$taxonomy->config['fpname'] = 'pname';
			$taxonomy->config['fcname'] = 'cname';
			$taxonomy->config['fpid'] = 'pid';
			$taxonomy->config['fcid'] = 'cid';
			
			echo $taxonomy->attach(35, 49);
			echo $taxonomy->attach(35, 50);
			echo $taxonomy->attach(35, 51);
			*/
			
			//echo $taxonomy->detach(215, 23);
			//echo $taxonomy->make_sql('SELECT count(*) as cnt FROM {links} WHERE {linkname} AND {cid}=23');
			
			//if (!$taxonomy->attached('215', '23'))
			//	$taxonomy->attach('215', '23');
			//echo '<pre>';
			//print_r($data);
			//echo '</pre>';
			
			/*
			// 5. Получить документы привязанные к 23.
			$taxonomy->config['table'] = $mvc->parse('{dbpref}owners');
			$taxonomy->config['ptable'] = '{dbpref}site_content';
			$taxonomy->config['ctable'] = '{dbpref}site_content';
			$taxonomy->config['pname'] = 'pname';
			$taxonomy->config['cname'] = 'cname';
			$taxonomy->config['pid'] = 'pid';
			$taxonomy->config['cid'] = 'cid';
			
			$data = $taxonomy->get_data('SELECT _ctable.id, _ctable.pagetitle FROM {from} WHERE {linkage}');
			echo '<pre>';
			print_r($data);
			echo '</pre>';
			
			// 6. Отвязать все от документа 23.
			$taxonomy->config['links'] = $mvc->parse('{dbpref}owners');
			$taxonomy->config['ptable'] = '{dbpref}site_content';
			$taxonomy->config['ctable'] = '{dbpref}site_content';
			$taxonomy->config['fpname'] = 'pname';
			$taxonomy->config['fcname'] = 'cname';
			$taxonomy->config['fpid'] = 'pid';
			$taxonomy->config['fcid'] = 'cid';
			
			$mvc->bm->add('prepare');
			
			//$data = $taxonomy->get_data('DELETE FROM {links} WHERE {pid}=23');
			$query = $taxonomy->make_sql('SELECT {ctable}.pagetitle FROM {from} WHERE {where}');
			$mvc->bm->add('prepared');

			$data = $mvc->db->get_data($query);
			echo $sql;
			echo '<pre>';
			print_r($data);
			echo '</pre>';			
			
			*/
			
			
			
			
			
			
			
			
			/*
			
			$taxonomy->config['table'] = $mvc->parse('{dbpref}site_tmplvar_templates');
			$taxonomy->config['pname'] = '';
			$taxonomy->config['cname'] = '';
			$taxonomy->config['pid'] = 'templateid';
			$taxonomy->config['cid'] = 'tmplvarid';

			$taxonomy->config['table'] = $mvc->parse('{dbpref}owners');
			$taxonomy->config['pname'] = 'pname';
			$taxonomy->config['cname'] = 'cname';
			$taxonomy->config['pid'] = 'pid';
			$taxonomy->config['cid'] = 'cid';
			*/
			
			//echo '<pre>';
			//$taxonomy->attach('{dbpref}site_content', 10, '{dbpref}site_templates', 20); // Прикрепить узел.
			//$childs = $taxonomy->get_attached('items2', 2); // Получить прикрепленный узел.
			// [0] - childs, 1 - parent
			

			//print_r($childs);
			//print_r($childs = $taxonomy->get_attached('{dbpref}site_templates', 4 /* [0] - childs, 1 - parent */));
			//print_r($childs = $taxonomy->get_attached('{dbpref}site_content', 1, 1 /* [0] - childs, 1 - parent */));
			//$taxonomy->get_data($childs);//, '{dbpref}site_templates');
			//echo '</pre>';
			//$childs = $taxonomy->get_attached('{dbpref}site_templates', 20);
			


			
			//$this->test_tree();
			//$taxonomy->attach('table1', $row1['id'], 'table2', $row2['id']); // = INSERT INTO {links}(cname, cid, paname, pid) VALUES('','','','');
			//$taxonomy->attach('', '#', '', '#');
			//$taxonomy->detach($row1, $row2);
			//$taxonomy->get_atteches($row2);			
			//$taxonomy->get_atteches($row2);
			
			/*
			// Garbage
			$tpls = $mvc->db->get_data($mvc->parse('SELECT id,templatename FROM {dbpref}site_templates'));
			foreach($tpls as $row)
			{
				echo $row['templatename'].':';
				$items = $mvc->db->get_data($mvc->parse('SELECT id,templatename FROM {dbpref}site_templates'));
				echo '<br>';
			}
			print_r($tpls);

			
			$sql = 'SELECT sc.id, sc.parent, sc.pagetitle, sc.template, st.templatename 
				FROM {dbpref}site_content sc, {dbpref}site_templates st
				WHERE sc.template=st.id';
			
			//$mvc->load_module('dbnode', false);
			//$dbnode = new CDbnode('', );
			
			$data = $mvc->db->get_data($mvc->parse($sql));
			//print_r($data);
			*/
			

			
			/*
			// Test DBNode.
			$mvc->load_module('dbnode', false);			
			$item = new CDbnode('shop', 1);
			$item2 = new CDbnode('brand', 3);			
			echo '<pre>';
			//$item->attach('brand', array(1, 2, 3));
			//$item->attach($item2);
			//$item->detach($item2);
			print_r($item->getChilds());
			//print_r($item->fields);
			//$item->attach($item2);
			//echo '<br>';
			//$item->detach('brand', '4,5,6,7');
			die();
			*/
			
			//echo '<pre>';
			//print_r($mvc->db->get_fields('shop'));
			//$data = array();
			//$data['id'] = 50;
			//$data['name'] = 'frank';
			//$mvc->bd->set_data('shop', $data);
			//$data = array('name' => 'djon');
			
			//echo '['.(int)$mvc->db->table_exists('shop').']';
			//$fields = $mvc->db->get_fields('link3');
			//echo '<pre>';
			//print_r($fields);
			//echo '</pre>';
			//unset($fields['id']);
			//unset($fields['comment']);// = array('type' => 'int');
			//$mvc->db->set_fields('link3', $fields);
			
			//$mvc->db->query('DROP TABLE IF EXISTS link2');
			//$mvc->db->query('DROP TABLE IF EXISTS link3');
			
			/*
			// Test CTree.
			$mvc->bm->add('test ctree');
			$tree_builder = $mvc->load_module('tree'); // Загружаем и созадем класс.
			$mvc->bm->add('ctree loaded');
			
			//$data = $mvc->db->get_data('SELECT id, parent, pagetitle FROM modx_site_content');	 // Получаем данные из БД.
			$data = $mvc->db->get_data('SELECT * FROM modx_site_content');	 // Получаем данные из БД.
			$mvc->bm->add('data loaded');
			
			$tree_builder->config['field_pid'] = 'parent'; // Натсриваем конфиг.
			$tree = $tree_builder->build($data);			
			$mvc->bm->add('tree created');			
			
			// Template fuction.
			function fff($item, $mode, $addon = 0)
			{
				$level = (int)$item['_level'];

				$html = '';
				
				if ($mode == 0)
				{
					if ($level > 0)
						$html .= '<li>'.$item['pagetitle'].'<b>'.htmlspecialchars($addon['outer0']).'</b>';

					if (isset($item['_childs']))
						$html .= '<ul>';
				}
				else
				{
					if (isset($item['_childs']))
						$html .= '</ul>';
					
					if ($level > 0)
						$html .= '</li>';
				}
				
				return $html;
			}
			
			echo '<hr color="red">';
			$mvc->bm->add('bef walk');
			
			echo $tree_builder->walk($tree, 
				array($this, 'go'), 
				array('outer' => '<ul>|</ul>', 'inner' => '<li>{name}</li>|')
			);
			//echo $tw->walk($tree, fff, array('outer0' => '<ul>', 'outer1' => '</ul>', 'inner' => '<li>{name}</li>|'));
			//echo $tw->render($tree, '<ul>|</ul>', '<li>{id}+{pid} - {pagetitle}|</li>');
			
			//echo $tw->render($tree, '<ul>|</ul>', '<li>{pagetitle}|</li>');
			//echo $tw->render($tree);
			//echo $tw->render($tree);
			$mvc->bm->add('aft walk');
			echo '<hr color="green">';
			/**/			
			


//echo '<pre>';
			//$mvc->bm->calc();
			$mvc->bm->add('finish');
			echo $mvc->view->render('system/bm_default', $mvc->bm->points);
			echo $mvc->view->render('system/mody_messages', $mvc->messages);
			
			//print_r($mvc->args);
			//$ins = $mvc->load_module('insertion');
			//echo $ins->parse('[[ins1]]');
			
			
			//$data = $mvc->db->get_data('SELECT * FROM shop WHERE id > 5');
			//$mvc->db->del_data('shop',  $data);
			
			//$data = $mvc->db->get_data('SELECT * FROM shop');
			//$data[] = array('name' => 'valentin');
			//$mvc->db->set_data('shop', $data);
			//$mvc->db->set_data('shop', $data);
			//$mvc->db->set_data('shop', $data);
			//$mvc->db->set_data('shop', $data);
			
			//print_r($data);
			
			
			//echo '</pre>';
			return;
			
			$r = $mvc->db->query('SELECT * FROM mody_insertions');			
			$mvc->db->make_tree($r); // Создать дерево.
			
			$tw = $mvc->load_module('db/tree_walker');
			$tree = $tw->build($r);
			$tw->walk($tree);
			
			
			while($a = mysql_fetch_row($r))
			{
				print_r($a);
				echo '<br>';
			}
			
		
			echo 'Default controller. args<pre>';
			print_r($args);
			echo '</pre>';
		}
		
		function test_benchmark()
		{
			global $mvc;
			
			// Benchmark test.
			$mvc->bm->add('bm test start');
			$mvc->bm->add('bm test');
			$mvc->bm->add('bm test');
			$mvc->bm->add('bm test');
			$mvc->bm->add('bm test');
			$mvc->bm->add('bm test');
			$mvc->bm->add('bm test');
		}
		
		function test_dbapi()
		{
			global $mvc;
			$mvc->bm->add('test_dbapi');
			$fileds1 = $mvc->db->get_fields('modx_site_content');
			$mvc->bm->add('get fields');
			$mvc->db->set_fields('modx_site_content', $fileds1);
			$mvc->bm->add('set fields');
			$fileds2 = $mvc->db->get_fields('modx_site_content');
			$mvc->bm->add('get fields');
			
			// ...
		}
		
		function test_tree()
		{
			global $mvc;
			
			// Test CTree.
			$mvc->bm->add('test ctree');
			$tree_builder = $mvc->load_module('tree'); // Загружаем и созадем класс.
			$mvc->bm->add('ctree loaded');
			
			//$data = $mvc->db->get_data('SELECT id, parent, pagetitle FROM modx_site_content');	 // Получаем данные из БД.
			$data = $mvc->db->get_data('SELECT * FROM modx_site_content');	 // Получаем данные из БД.
			$mvc->bm->add('data loaded');
			
			$tree_builder->config['field_pid'] = 'parent'; // Натсриваем конфиг.
			$tree = $tree_builder->build($data);			
			$mvc->bm->add('tree created');			
			
			// Template fuction.
			function fff($item, $mode, $addon = 0)
			{
				$level = (int)$item['_level'];

				$html = '';
				
				if ($mode == 0)
				{
					if ($level > 0)
						$html .= '<li>'.$item['pagetitle'].'<b>'.htmlspecialchars($addon['outer0']).'</b>';

					if (isset($item['_childs']))
						$html .= '<ul>';
				}
				else
				{
					if (isset($item['_childs']))
						$html .= '</ul>';
					
					if ($level > 0)
						$html .= '</li>';
				}
				
				return $html;
			}
			
			echo '<hr color="red">';
			$mvc->bm->add('bef walk');
			
			echo $tree_builder->walk($tree, 
				array($this, 'go'), 
				array('outer' => '<ul>|</ul>', 'inner' => '<li>{name}</li>|')
			);
			//echo $tw->walk($tree, fff, array('outer0' => '<ul>', 'outer1' => '</ul>', 'inner' => '<li>{name}</li>|'));
			//echo $tw->render($tree, '<ul>|</ul>', '<li>{id}+{pid} - {pagetitle}|</li>');
			
			//echo $tw->render($tree, '<ul>|</ul>', '<li>{pagetitle}|</li>');
			//echo $tw->render($tree);
			//echo $tw->render($tree);
			$mvc->bm->add('aft walk');
			echo '<hr color="green">';		
		}
	}
?>